package top.mcwebsite.playandroid.lib.markdown.render

import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import top.mcwebsite.playandroid.lib.markdown.BlockVerticalPadding

internal fun getDefaultHeadingStyle(astNode: ASTNode, textStyle: TextStyle) =
    when (astNode.type) {
        MarkdownElementTypes.ATX_1, MarkdownElementTypes.SETEXT_1 ->
            textStyle.copy(fontSize = 28.sp, fontWeight = FontWeight.Bold)

        MarkdownElementTypes.ATX_2, MarkdownElementTypes.SETEXT_2 ->
            textStyle.copy(fontSize = 26.sp, fontWeight = FontWeight.Bold)

        MarkdownElementTypes.ATX_3 ->
            textStyle.copy(fontSize = 22.sp, fontWeight = FontWeight.Bold)

        MarkdownElementTypes.ATX_4 ->
            textStyle.copy(fontSize = 20.sp, fontWeight = FontWeight.Bold)

        MarkdownElementTypes.ATX_5 ->
            textStyle.copy(fontSize = 18.sp, fontWeight = FontWeight.Bold)

        MarkdownElementTypes.ATX_6 ->
            textStyle.copy(fontSize = 16.sp, fontWeight = FontWeight.Bold)

        else -> textStyle
    }

@Composable
fun Heading(markdownState: MarkdownState, astNode: ASTNode) {
    val contentAstNode =
        if (astNode.type == MarkdownElementTypes.SETEXT_1 || astNode.type == MarkdownElementTypes.SETEXT_2) {
            astNode.children.find { it.type == MarkdownTokenTypes.SETEXT_CONTENT }
        } else {
            astNode.children.find { it.type == MarkdownTokenTypes.ATX_CONTENT }
        }

    RichText(
        markdownState = markdownState,
        astNode = contentAstNode,
        style = getDefaultHeadingStyle(astNode, TextStyle().copy(lineHeight = TextUnit.Unspecified)),
        modifier = Modifier.padding(vertical = BlockVerticalPadding)
    )

}
